<?php
namespace Admin\Model;

use Think\Model;

class ClassManagerModel extends Model {

    /**
     * 根据老师id,查询该老师所管理的所有班级id
     *
     * @param $tid
     * @return array
     */
    public function getClassIdsByTid($tid) {

        $map['teacher_id'] = $tid;
        $res = $this->where($map)->find();
        if (empty($res)) return null;

        $ids = explode(',',$res['class_id']);
        if (empty($ids)) return null;

        return $ids;
    }

    public function getClassManagerIdByTid($tid) {
        return $this->where('teacher_id = ' .$tid)->getField('id');
    }


    /**
     * 根据班级ID,查询该班级的教师ID
     *
     * @param $cid
     * @param $did 系别ID,非必要。辅助字段,减少查询数据库操作
     * @return int | array
     */
    public function getTidByCid($cid,$did=null) {

        $map = null;
        !is_null($did) && $map['department_id'] = $did;
        is_null($map) && $map = '';
        $res = $this->where($map)->select();

        foreach ($res as $k=>$v) {
            $arr = explode(',',$v['class_id']);
            if (in_array($cid,$arr)) {
                return $v['teacher_id'];
            }
        }

        return false;
    }


    public function getAllTeacherIds() {
        $res = $this->select();
        if (empty($res)) return array();

        $tids = array ();
        foreach ($res as $val) {
            array_push($tids,intval($val['teacher_id']));
        }
        return $tids;
    }


    public function getAllClassIds($where = '') {
        $res = $this->where($where)->select();
        if (empty($res)) return array();

        $cids = array();
        foreach ($res as $val) {
            if (empty($val['class_id'])) continue;
            $arr = explode(',',$val['class_id']);
            $cids = array_merge($cids,$arr);
        }
        return \Api\Libs\ToolsUtil::toInt($cids);
    }



    public function _get($id) {
        return $this->find($id);
    }

    public function _add($data) {
        $map['teacher_id'] = $data['teacher_id'];
        $res = $this->where($map)->find();
        if (!empty($res)) return '100801';

        $flag = $this->add($data);
        if ($flag !== false) return '000000';
        return '111111';
    }


    public function _edit($data) {
        $flag = $this->save($data);
        if ($flag !== false) return '000000';
        return '111111';
    }


    public function _del($id) {
        $flag = $this->delete($id);
        if ($flag !== false) return'000000';
        return '111111';
    }

}